<template>
  <el-container>
    <el-header>
      <searchCOM @search="handleSearch"></searchCOM>
      <el-button @click="dialogAddNewFileCategoryVisible = true" style="float: right">新增归档分类</el-button>
    </el-header>
    <tableCOM ref="table" @deleteSelectionA="deleteSelection" @handleSizeChangeA="handleSizeChange" @handleCurrentChangeA="handleCurrentChange"
              @handleSelectionChangeA="handleSelectionChange" @toggleSelectionA="toggleSelection" :tableHeadData="tableHeadData" :tableData="tableData" :operator="operator" :page="page" :pageSize="pageSize" :counts="counts"></tableCOM>
    <editCOM @edit="editConfirm" @dialogEdit="dialogEditClose" :dialogEditVisible="dialogEditVisible" :tableHeadData="tableHeadData"
             :selectList="selectList" :dataUpdate="dataUpdate" :rules="rules"></editCOM>
    <el-dialog :visible.sync="isSort">
      <el-select v-model="sortId" placeholder="请选择归档分类">
        <template v-for="(item,index) in selectList.sortList">
          <el-option
              :key="index"
              :label="item.name"
              :value="item.id">
          </el-option>
        </template>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isSort = false">取 消</el-button>
        <el-button type="primary" @click="sort(rowData)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogAddNewFileCategoryVisible">
      <el-form :rules="rules" :model="addFC" ref="addFC">
        <el-form-item prop="addFC" label="请输入需要新增的归档分类名">
          <el-input v-model="addFC.addFC"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddNewFileCategoryVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewFC()">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import DialogOne from "@/components/DialogOne";

import {
  apiFileSendAccept,
  apiFileSendAdd,
  apiFileSendDel,
  apiFileSendList,
  apiFileSendSelf, apiFileSendUnAccept,
  apiFileSendUpdate
} from "@/assets/api/FileSendAPI";
import searchCOM from "@/components/searchCOM";
import editCOM from "@/components/editCOM";
import tableCOM from "@/components/tableCOM";
import {apiFileCategoryAdd, apiFileCategoryListAll, apiFileCategoryListSelf} from "@/assets/api/FileCategoryAPI";
import {apiFileCategoryListSort} from "@/assets/api/FileCategoryListAPI";
import {download, downloadExist} from "@/assets/api/FileAPI";
import state from "@/store/state";
export default {
  components: {tableCOM, editCOM, searchCOM, DialogOne},
  data(){
    return{
      tableHeadData: [
        {label: '源用户', width: '', prop: `fromUser`,table: true},
        {label: '目标用户', width: '', prop: `toUser`,table: true},
        {label: '发件用户', width: '', prop: `fromUserName`},
        {label: '收件用户', width: '', prop: `toUserName`,table:true},
        {label: '文件', width: '', prop: `file`,table:true},
        {label: '文件', width: '', prop: `fileUrl`,form:true},
        {label: '状态(0:未接收,1:已接收,2:已退回)', width: '', prop: `status`,type:'radio',radio:[
            {label:'0',name:'已发送'},
            {label:'1',name:'已接收'},
            {label:'2',name:'已退回'},
          ],Formate:true},
      ],
      dataStandard :{
        fromUser:'',
        toUser:'',
        file:'',
        status:'',
      },
      rules:{
        fromUser: [{required: true, message: '源用户不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        toUser: [{required: true, message: '目标用户不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        addFC: [{required: true, message: '不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        file: [{required: true, message: '文件不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        status: [{required: true, message: '状态(0:已发送,1:已接收,2:已退回)不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
      },
      operator:[
        {'text':'拒绝', click: (row, col, cellValue) => {return this.unAccept(row)},
          isShow: (row, $index) => {
            if(row.status != '0'){
              return true;
            }
            return false;
          }},
        {'text':'接收', click: (row, col, cellValue) => {return this.accept(row)},
          isShow: (row, $index) => {
            if(row.status != '0'){
              return true;
            }
            return false;
          }},
        {'text':'下载', click: (row, col, cellValue) => {return this.download(row)},
          isShow: (row, $index) => {
            if(row.status == '1'){
              return false;
            }
            return true;
          }},
        {'text':'归档', click: (row, col, cellValue) => {

            return this.changeIsSort(row)
          },
          isShow: (row, $index) => {
            if(row.status == '1'){
              return false;
            }
            return true;
          }},
      ],
      searchDate:[],
      selectList:[],
      dataUpdate :{},
      pageSize: 10,
      counts:0,
      page:1,
      searchName:'',
      branch:false,
      dialogEditVisible:false,
      multipleSelection:[],
      deleteID:[],
      tableData:[],
      isSort:false,
      way:1,
      dialogAddNewFileCategoryVisible:false,
      rowData:'',
      sortId:'',
      addFC:{
        addFC:''
      }
    }
  },
  created() {
    this.initList()
    this.init()
  },
  methods: {
    parentSubmit(){
      apiFileSendAdd(this.dataUpdate)
      this.init()

    },
    receive(var1){
      this.dataUpdate = var1;
      this.parentSubmit()
    },
    async init () {
      const params = {
        page: this.page,
        pageSize: this.pageSize,
        name: this.searchName ? this.searchName : undefined,
        sortId: this.searchDate.sortId ? this.searchDate.sortId : undefined,
        way:this.way,
      }
      apiFileSendSelf(params).then(resp => {
        this.tableData = resp.data.data.records,
            this.counts = resp.data.data.total
      })
    },
    accept(row){
      const p ={
        id:row.id
      }
    apiFileSendAccept(p).then(
        resp => {
          if(resp.data.code === 1){
            this.$message.success("成功")
          }else {
            this.$message.error(resp.data.msg)
          }
          this.init()

        }
    )
    },
    changeIsSort(row){
      this.rowData = row
      this.isSort = true
      console.log(this.isSort)
    },
    unAccept(row){
      const p ={
        id:row.id
      }
      apiFileSendUnAccept(p).then(
          resp => {
            if(resp.data.code === 1){
              this.$message.success("成功")
            }else {
              this.$message.error(resp.data.msg)
            }
            this.init()

          }
      )
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.table.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.table.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      let checkArr = []
      val.forEach((n) => {
        checkArr.push(n.id)
      })
      this.multipleSelection = checkArr;
    },
    deleteSelection(){
      this.branch = true
      this.del()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.init()
    },
    handleCurrentChange(val) {
      this.page = val
      this.init()
    },
    del(rowId){
      this.deleteID = this.branch ? this.multipleSelection : rowId
      if (this.deleteID.length === 0 && this.branch) {
        return this.$message.error('请选择删除对象')
      }
      this.$confirm('确认删除, 是否继续?', '确定删除', {
        'confirmButtonText': '确定',
        'cancelButtonText': '取消',
      }).then(() => {
        console.log(this.branch)
        apiFileSendDel(this.branch ? this.deleteID.join(",") : this.deleteID).then(resp =>{
          if (resp.data.code === 1){
            this.$message.success("成功")
          }
        })
        this.branch = false
        this.init()
      })
    },
    edit(row){
      this.dialogEditVisible = true
      this.dataUpdate = JSON.parse(JSON.stringify(row))
    },
    dialogEditClose(){
      this.dialogEditVisible = false
    },
    editConfirm(data){
      apiFileSendUpdate(data).then(resp => {
        if(resp.data.code === 1){
          this.$message.success("成功")
        }else {
          this.$message.error(resp.data.msg)
        }
        this.init()
      })
      this.dialogEditVisible = false
    },
    handleSearch(name) {
      this.searchName = name
      this.page = 1;
      this.init();
    },

    download(row){
      const p ={
        name:row.fileUrl,
        id:row.file,
        typeId:row.typeId
      }
      if (row.fileUrl === '' || row.fileUrl===null){
        console.log(row.url === '')
        downloadExist(p).then(res =>{
          console.log(res);
          if (!res.data) {
            return;
          }
          if (state.userInfo == null){
            return;
          }
          var name = row.title + ".pdf";
          let blob = new Blob([res.data], {
            type: "application/vnd.ms-excel;charset=utf-8",
          });
          var url = window.URL.createObjectURL(blob);
          var aLink = document.createElement("a"); //创建a标签
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", name); // 设置文件 name
          document.body.appendChild(aLink);
          aLink.click(); //自执行下载
          document.body.removeChild(aLink); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }).catch((error) => {});
        return
      }
      download(p).then(res =>{
        console.log(res);
        if (res.data.size == 0) {
          return this.$message.error("权限不足");
        }
        if (state.userInfo == null){
          return;
        }
        var name = row.fileName + ".pdf";
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        var url = window.URL.createObjectURL(blob);
        var aLink = document.createElement("a"); //创建a标签
        aLink.style.display = "none";
        aLink.href = url;
        aLink.setAttribute("download", name); // 设置文件 name
        document.body.appendChild(aLink);
        aLink.click(); //自执行下载
        document.body.removeChild(aLink); //下载完成移除元素
        window.URL.revokeObjectURL(url); //释放掉blob对象
      })
          .catch((error) => {});
    },
    initList(){
      apiFileCategoryListSelf().then(res =>{
        this.selectList.sortList = res.data.data
      })
    },

    addNewFC(){
      const p = {
        name: this.addFC.addFC
      }
      apiFileCategoryAdd(p).then(res =>{
        if(res.data.code == 1){
          this.$message.success("成功")
        }else {
          this.$message.error(res.data.msg)
        }
        this.dialogAddNewFileCategoryVisible = false
        this.addFC.addFC = ''
        this.initList()
      })
    },

    sort(row){
      console.log(row)
      const params = {
        sortId: this.sortId,
        fileId: row.file
      }
      apiFileCategoryListSort(params).then(res =>{
        if(res.data.code == 1){
          this.$message.success("归档成功")
        }else {
          this.$message.error(res.data.msg)
        }
        this.isSort = false
        this.init()
      })


    }

  },
}
</script>
<style scoped>
</style>